package cn.stylefeng.guns.modular.system.service;

import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.mapper.ExamUserMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author zfy
 * @since 2020-08-12
 */
@Service
public class ExamUserService extends ServiceImpl<ExamUserMapper,ExamUser> {

    @Autowired
    private ExamService examService;
    @Autowired
    private ExamPlaceClassService examPlaceClassService;
    @Autowired
    private ExamPayLogService examPayLogService;
    @Autowired
    private SysStudentService studentService;
    @Autowired
    private ExamUserService examUserService;
    @Autowired
    private ExamResultUserService examResultUserService;
    @Autowired
    private SysSchoolAgentService sysSchoolAgentService;
    @Autowired
    private RedisTemplate redisTemplate;


    public void userSignUp (String out_trade_no,String transaction_id,Double total_fee ){
        System.out.println("成功:付款金额---" + total_fee + "*商户订单号---" + out_trade_no + "*微信支付订单号--" + transaction_id + "*");
        String examText = (String) redisTemplate.opsForHash().get("exam", out_trade_no);
        if(ToolUtil.isNotEmpty(examText)){
            JSONObject json = JSON.parseObject(examText);
            examPayLogService.add (json.getString("examIds"),
                    json.getString("userIds"),
                    out_trade_no,transaction_id,
                    total_fee,
                    json.getString("createUser"));
            Arrays.asList(json.getString("examIds")).forEach(examId->{
                Arrays.asList(json.getString("userIds")).forEach(userId->{
                    userSignUp(examId,userId);
                });
            });
        }
    }

    public void userSignUp (String examId,String userId){
        if(isExamUser(examId,userId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Long examPlaceId = examService.getById(examId).getExamPlaceId();
        SysStudent student = studentService.getStudent(Long.parseLong(userId));
        Map<String,Object> placeClass = examPlaceClassService.getClassNum(examPlaceId);
        ExamUser examUser = new ExamUser();
        examUser.setExamId(Long.parseLong(examId));
        examUser.setUserId(Long.parseLong(userId));
        examUser.setSchoolUserId(student.getCreateUser());
        examUser.setExamPlaceClassId(Long.parseLong(placeClass.get("classId").toString()));
        examUser.setAdmissionCardNo(student.getStudentCode()+placeClass.get("classNum").toString());
        examUser.setCreateTime(LocalDateTime.now());
        this.save(examUser);
    }

    public Boolean isExamUser (String examId,String userId){
        ExamUser examUser = this.getOne(new QueryWrapper<ExamUser>()
                .eq("exam_id", examId).eq("user_id", userId));
        return examUser == null ?false:true;
    }

    public Map<String,Object> getExamUserInfoByCode(String studentCode) {
        Map<String,Object> map = studentService.studentInfo(studentCode);
        if(!map.isEmpty()){
            List<Map<String,Object>> list = examUserService.listMaps(new QueryWrapper<ExamUser>()
                    .eq("user_id", map.get("user_id").toString()));
            list.forEach(listMap->{
                Exam exam = examService.getById(listMap.get("exam_id").toString());
                listMap.put("examTitle", exam.getExamTitle());
                listMap.put("exam", exam);
                listMap.put("examResultUserList",
                        examResultUserService.examResultUserList(Long.parseLong(map.get("user_id").toString()),
                                exam.getExamId()));
            });
            map.put("exam_user",list);
        }
        return map;
    }

    public List<Map<String,Object>> examUser(String name, Long createUser) {
        return this.baseMapper.examUser(name,createUser);
    }

    public IPage<Map<String,Object>> examSignUpList() {
        String[] createUsers = null;
        if(!ShiroKit.isAdmin()){
            createUsers = sysSchoolAgentService.getSchoolByAgent().split(",");
        }
        return this.baseMapper.examSignUpList(LayuiPageFactory.defaultPage(),createUsers);
    }
}
